package core.database;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@MappedSuperclass
public abstract class AbstractAuditEntity extends AbstractEntity {
	@Column(name = "created_on", insertable = true, updatable = false, nullable = false)
	@Temporal(TemporalType.TIMESTAMP)
	private Date createdOn;

	@Column(name = "last_modified_on", insertable = false, updatable = true)
	@Temporal(TemporalType.TIMESTAMP)
	private Date lastModifiedOn;

	@Column(name = "created_by", insertable = true, updatable = false, nullable = false)
	private String createdBy;

	@Column(name = "last_modified_by", insertable = false, updatable = true)
	private String lastModifiedBy;

	@PrePersist
	protected void onCreate() {
		this.createdOn = new Date();
		this.createdBy = getCurrentUsersUsername();
	}

	@PreUpdate
	protected void onUpdate() {
		this.lastModifiedOn = new Date();
		this.lastModifiedBy = getCurrentUsersUsername();
	}

	private String getCurrentUsersUsername() {
		// TODO: pobieranie aktualnego użytkownika
		Object os = null;
		// Object os = SecurityContextHolder.getContext().getAuthentication() != null ? SecurityContextHolder
		// .getContext().getAuthentication().getPrincipal()
		// : null;

		if (os == null || !(os instanceof String)) {
			return "@SYSTEM";
		} else {
			return (String) os;
		}
	}

	public Date getCreatedOn() {
		return createdOn;
	}

	public void setCreatedOn(Date createdOn) {
		this.createdOn = createdOn;
	}

	public Date getLastModifiedOn() {
		return lastModifiedOn;
	}

	public void setLastModifiedOn(Date lastModifiedOn) {
		this.lastModifiedOn = lastModifiedOn;
	}

	public String getCreatedBy() {
		return createdBy;
	}

	public void setCreatedBy(String createdBy) {
		this.createdBy = createdBy;
	}

	public String getLastModifiedBy() {
		return lastModifiedBy;
	}

	public void setLastModifiedBy(String lastModifiedBy) {
		this.lastModifiedBy = lastModifiedBy;
	}

	// @Override
	// public String toString() {
	// return ToStringBuilder.reflectionToString(this);
	// }
}
